package org.libjpopup.sender;

import jpcap.JpcapCaptor;
import jpcap.JpcapSender;
import jpcap.NetworkInterface;
import jpcap.NetworkInterfaceAddress;
import jpcap.packet.ARPPacket;
import jpcap.packet.EthernetPacket;

import java.net.InetAddress;
import java.util.Arrays;

public class ARP {                                 //code was taken from jpcap tutorial

    public static byte[] arp(JpcapCaptor captor, JpcapSender sender, NetworkInterface networkInterface, NetworkInterfaceAddress networkInterfaceAddress, InetAddress ip) {
        InetAddress srcip = networkInterfaceAddress.address;
        byte[] broadcast = Sender.BROADCAST_HWADDR;
        ARPPacket arp = new ARPPacket();
        arp.hardtype = ARPPacket.HARDTYPE_ETHER;
        arp.prototype = ARPPacket.PROTOTYPE_IP;
        arp.operation = ARPPacket.ARP_REQUEST;
        arp.hlen = 6;
        arp.plen = 4;
        arp.sender_hardaddr = networkInterface.mac_address;
        arp.sender_protoaddr = srcip.getAddress();
        arp.target_hardaddr = broadcast;
        arp.target_protoaddr = ip.getAddress();
        EthernetPacket ether = new EthernetPacket();
        ether.frametype = EthernetPacket.ETHERTYPE_ARP;
        ether.src_mac = networkInterface.mac_address;
        ether.dst_mac = broadcast;
        arp.datalink = ether;
        sender.sendPacket(arp);
        while (true) {          //todo: use timeout
            ARPPacket p = (ARPPacket) captor.getPacket();
            if (Arrays.equals(p.target_protoaddr, srcip.getAddress())) {
                return p.sender_hardaddr;
            }
        }
    }
}
